package com.tnsw.facebookautoliker.helper.command;

import java.util.ArrayList;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.os.AsyncTask;

import com.facebook.Session;
import com.facebook.model.GraphUser;
import com.tnsw.coreutils.MyLog;
import com.tnsw.coreutils.database.RecordBase;
import com.tnsw.coreutils.http.THttpBase;
import com.tnsw.coreutils.http.THttpGet;
import com.tnsw.coreutils.http.THttpListener;
import com.tnsw.facebookautoliker.database.DBManager;
import com.tnsw.facebookautoliker.database.FriendsList;
import com.tnsw.facebookautoliker.helper.FacebookBGManager;
import com.tnsw.facebookautoliker.helper.FacebookCommandObject;
import com.tnsw.facebookautoliker.helper.GeneralManager;
import com.tnsw.facebookautoliker.services.AutoLikerService;

public class GetPhoto extends FacebookCommandObject implements THttpListener {

	private Context context;
	private String tag = "";
	private String id;
	private String name;
	
	private THttpGet httpFirst;
	private THttpGet httpImage;
	
	private DBManager dbm;
	private FacebookBGManager fbm;
	private GeneralManager gm;
	
	private String extension = "";
	private String photosize = "normal";
	private String photoFileName = "";
	private String signature;
	
	public GetPhoto(Context context, GraphUser graphUser) {
		super(context);
		this.context = context;
		this.tag = "GetPhoto:" + graphUser.getId();
		this.id = graphUser.getId();
		this.name = graphUser.getName();
		
		this.signature = this.getClass().getName() + "_" + this.id;
		this.initialize();
	}
	
	public GetPhoto(Context context, String id, String name) {
		super(context);
		this.context = context;
		this.tag = "GetPhoto:" + id;
		this.id = id;
		this.name = name;
		
		this.signature = this.getClass().getName() + "_" + this.id;
		this.initialize();
	}
	
	private void initialize() {
		this.dbm = DBManager.getInstance(context);
		this.fbm = FacebookBGManager.getInstance(context);
		this.gm = GeneralManager.getInstance();
	}
	
	public String getPhotoFileName() {
		return(this.photoFileName);
	}
	
	public void setPhotoSize(String size) {
		this.photosize = size;
	}
	
	public String getPhotoSize() {
		return(this.photosize);
	}
	
	public String getId() {
		return(this.id);
	}
	
	private void prepareHeader(THttpBase http, String url) {

		http.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		http.addHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
		http.addHeader("Accept-Encoding", "gzip,deflate,sdch");
		http.addHeader("Connection", "keep-alive");
		http.addHeader("Accept-Language", "th,en-US;q=0.8,en;q=0.6");
		http.addHeader("Host", THttpBase.getHost2(url));
		http.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4");
		http.setListener(this);
	}

	@Override
	public void execute() {
		super.execute();
		
		//?width=300&height=300
		String url = "https://graph.facebook.com/" + this.id + "/picture?type=" + this.photosize;
		
		url = "https://graph.facebook.com/" + this.id + "/picture?width=300&height=300";
		
		Session session = Session.getActiveSession();
		if (session != null) {
			url = url + "&access_token=" + session.getAccessToken();
		}
		
		this.httpFirst = new THttpGet(context, url);
		
		HttpClient client = new DefaultHttpClient();
		client.getParams().setParameter("http.protocol.handle-redirects", false);
		this.httpFirst.setHttpClient(client);
		this.httpFirst.setSessionName("metadata");
		
		this.prepareHeader(this.httpFirst, url);
		this.httpFirst.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "0");
	}

	@Override
	public void onProgressUpdate(THttpBase sender, Integer[] values) {
		// TODO Auto-generated method stub
		
	}
	
	private void updateRecord(THttpBase sender) {
		ArrayList<RecordBase> a = this.dbm.getRecords("com.tnsw.facebookautoliker.database.FriendsList", "select * from friends_list where id=?", new String[] {this.id}, 0);
		if (a != null) {
			FriendsList fl = (FriendsList) a.get(0);
			fl.photo_path = sender.getCurrentBinaryfileName();
			
			this.dbm.updateRecordByPrimarykey("friends_list", fl, true);
			
			AutoLikerService aService = AutoLikerService.getInstance();
			aService.updateFriendsList(this.id, fl);
			
			MyLog.d(tag, "updated photo_path=" + sender.getCurrentBinaryfileName() + ", actor_id=" + this.id + ", name=" + this.name);
		} else {
			MyLog.e(tag, "not found record in friends_list, id=" + this.id + ", how come?");
		}
	}

	@Override
	public void onPostExecute(THttpBase sender, Long result) {

		if (sender == this.httpImage) {
			if (result == 0l) {
				this.photoFileName = sender.getCurrentBinaryfileName();
				this.updateRecord(sender);
			} else {
				MyLog.e(tag, "Cannot write photo for actor_id=" + this.id + ", name=" + this.name);
			}
			
			fbm.updateCommandStatus(this, 200, null);
		} else {
			if (result != 0l) {  // There is some error happen on 1st or 2nd http request, then, return token(result)
				if (sender.getHttpResponse() == null) {
					fbm.updateCommandStatus(this, -1, null);	
				} else {
					fbm.updateCommandStatus(this, sender.getHttpResponse().getStatusLine().getStatusCode(), null);
				}
					
			}
		}
		
		FriendsList fl = new FriendsList();
		fl.id = this.id;
		fl.name = this.name;
		
		this.dbm.updateFriendsListById(fl);
		
		if (sender == this.httpFirst) {
			if (result == 0l) {
				MyLog.d(tag, "HttpStatus=" + sender.getHttpResponse().getStatusLine().getStatusCode());
				if (sender.getHttpResponse().getStatusLine().getStatusCode() == 302) {
					String url = sender.getHttpResponse().getHeaders("Location")[0].getValue();
					this.httpImage = new THttpGet(context, url);
					this.httpImage.setBinaryDirection(THttpBase.BINARY_TO_FILE);
					this.httpImage.setSessionName("image");
					this.prepareHeader(this.httpImage, url);
					this.httpImage.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "0");
				}
			}
		}
		
	}

	@Override
	public void onNewLineFetchBG(THttpBase sender, String line) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onReceiveResponseBG(THttpBase sender) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onBinaryReadBG(THttpBase sender, byte[] b) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void interceptHandler(THttpBase sender) {
		
		try {
			if (sender.getSessionName().equals("metadata")) {
				String contentType = sender.getHttpResponse().getFirstHeader("Content-Type").getValue();
				this.extension = contentType.split("/")[1];
				MyLog.d(tag, "extension=" + this.extension);
				if (extension.equals("jpeg")) {
					this.extension = "jpg";
				
				}
				
			} else if (sender.getSessionName().equals("image")) {
				sender.setPredefinedExtension(this.extension);
				String filename = this.id + "." + this.extension;
				sender.setPredefinedFileName(filename);
			}
		} catch (Exception e) {
			MyLog.e(tag, "interceptHandler(session=" + sender.getSessionName() + ") - " + e.toString(), e);
		}

	}
	
	@Override
	public String getSignature() {
		return(this.signature);
	}	

}
